//
//  OAuthViewController.swift
//  WeiBoText
//
//  Created by 刘世瑛 on 16/1/16.
//  Copyright © 2016年 刘世瑛. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class OAuthViewController: UIViewController {

    
    let webView = UIWebView()
    override func viewDidLoad() {
        super.viewDidLoad()
        webView.delegate = self
        
       view = webView
     
        setNavNar()
        loadOAuthPage()
        // Do any additional setup after loading the view.
    }

    @objc private func close()
    {
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func defaultLogIn()
    {
        let string = "document.getElementById('userId').value = 'ruoruchujian641@sina.com',document.getElementById('passwd').value = 'mobai641'"
        webView.stringByEvaluatingJavaScriptFromString(string)
        
    }
   private func setNavNar()
    {
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defaultLogIn")
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    private  func loadOAuthPage()
    {
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + "3323554362" + "&" + "redirect_uri=" + "http://www.mobaifeimo.icoc.in"
        let url = NSURL(string: urlString)
        
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
    

}
extension OAuthViewController:UIWebViewDelegate
{
    func webViewDidStartLoad(webView: UIWebView) {
        print("start")
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        print("didLoad")
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        
        guard let urlString = request.URL?.absoluteString else{
            return false
        }
        
        if (urlString.containsString("code=")){
       
        guard  let query = request.URL?.query else
        {
            return false
        }
      
        let codeStr = "code="
        let code = (query as NSString).substringFromIndex(codeStr.characters.count)
        print(code)
            
            loadAccessToken(code)
            
            return false
        }
        return true
    }

    private func loadAccessToken(code:String)
{
   
    let urlString = "https://api.weibo.com/oauth2/access_token"
    let AFN = AFHTTPSessionManager()
    AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
    let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
    AFN.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
        print(result)
        
       guard let dic = result as? [String : AnyObject] else{
         print("数据格式不合法")
        
        return
        }
       let account = UserAccount(dict: dic)
        //获取用户信息
        self.loadUserInfor(account)
        }) { (_, error) -> Void in
            print(error)
    }
    }
    
    private func loadUserInfor(account:UserAccount)
    {
        //准备url 
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["access_token":account.access_token!,"uid":account.uid!]
        let AFN = AFHTTPSessionManager()
        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            
            print(result)
            
            guard let dict = result as? [String : AnyObject] else{
                
                return
            }
            
            let name = dict["name"] as! String
            let avatar_large = dict["avatar_large"] as! String
            
            account.name = name
            account.avatar_large = avatar_large
          
            account.saveInfor()
            }) { (_, error) -> Void in
                
                
                
        }
    }

}
